<template>
    <div class="kva-container-box">
        <div class="kva-container">
            <home-page-header>
                <div class="kva-from-search">
                    <el-form :inline="true" :model="pageInfo">
                        <el-form-item>
                            <el-button class="kva-button" type="primary" icon="Plus" @click="handleAddSysUser">添加用户</el-button>
                            <el-button class="kva-button" type="danger" icon="Delete" @click="handleBatchDel">删除用户</el-button>
                        </el-form-item>
                        <el-form-item label="关键词:" style="margin-left: 15px">
                            <el-input v-model="pageInfo.keyword" placeholder="请输入搜索关键词..." maxlength="10"/>
                        </el-form-item>
                        <el-form-item>
                            <el-button class="kva-button" type="primary" icon="Search" @click="handleSearch">搜索</el-button>
                            <el-button class="kva-button" type="warning" icon="Delete" @click="handleClear">清空</el-button>
                            <el-button class="kva-button" type="success" icon="Refresh" @click="handleLoadData">刷新</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 100%"
                          :height="settings.tableHeight()">
                    <el-table-column type="selection" fixed="left" width="30"/>
                    <el-table-column fixed="left" prop="id" label="ID"  align="center"/>
                    <el-table-column prop="account" label="账号"  align="center"/>
                    <el-table-column label="昵称" width="160" align="center">
                        <template #default="scope">
                            <el-avatar :size="small" :src="scope.row.avatar"></el-avatar>
                            <span style="position: absolute;padding-top: 10px;margin-left: 5px">{{
                                    scope.row.username
                                }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号" width="110" align="center"/>
                    <el-table-column prop="email" label="用户邮箱" width="180" align="center"/>
                    <el-table-column label="授予角色" align="center" width="246">
                        <template #default="{row,$index}">
                            <el-cascader
                                style="width: 100%;"
                                v-model="row.roleIds"
                                :options="rolesData"
                                @change="handleChangeRole(row)"
                                :props="props"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="冻结状态" align="center">
                        <template #default="scope">
                            <!-- 默认激活状态颜色 active-color="#ff0000"
                                 选中状态颜色   inactive-color="#00ff00" -->
                            <el-switch
                                v-model="scope.row.enable"
                                inline-prompt
                                size="large"
                                :active-value="1"
                                active-color="#ff0000"
                                active-text="冻结"
                                inactive-color="#00ff00"
                                inactive-text="正常"
                                :inactive-value="0"
                                @change="handleChangeStatus(scope.row,'enable')"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="删除状态" align="center">
                        <template #default="scope">
                            <!-- 默认激活状态颜色 active-color="#ff0000"
                                 选中状态颜色   inactive-color="#00ff00" -->
                            <el-switch
                                v-model="scope.row.isDeleted"
                                inline-prompt
                                size="large"
                                :active-value="1"
                                active-color="#ff0000"
                                active-text="已删除"
                                inactive-color="#00ff00"
                                inactive-text="未删除"
                                :inactive-value="0"
                                @change="handleChangeStatus(scope.row,'is_deleted')"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" width="160">
                        <template #default="scope">
                            {{ formatTimeToStr(scope.row.createTime, "yyyy-MM-dd hh:mm:ss") }}
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" align="center" width="160">
                        <template #default="scope">
                            {{ formatTimeToStr(scope.row.updateTime, "yyyy-MM-dd hh:mm:ss") }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="260" >
                        <template #default="{row,$index}">
                            <el-button link type="danger" icon="RemoveFilled" @click="handleDelete(row)">删除
                            </el-button>
                            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                            <el-button link type="success" icon="Switch" @click="handleResetPwd(row)">重置密码
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="kva-page">
                    <el-pagination
                        v-model:current-page="pageInfo.page"
                        v-model:page-size="pageInfo.pageSize"
                        :page-sizes="[10, 20, 30, 40]"
                        small
                        background
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </home-page-header>
        </div>
        <!-- 重置密码弹窗 -->
        <reset-password ref="userPwdRef"></reset-password>
        <!-- 添加和编辑弹窗 -->
        <add-sys-user ref="addSysUserRef" @load="handleLoadData"></add-sys-user>
    </div>
</template>

<script setup>
import settings from '@/settings';
import {kvaMessage} from "@/utils/kvaMessage.js";
import {FindPageData, UpdateStatus, DeleteById, DeleteByIds} from "@/api/sysUser.js"
import {FindData} from "@/api/sysRole.js"
import {SaveUserRole} from "@/api/sysUserRole.js"
import {formatTimeToStr} from '@/utils/date.js'
import ResetPassword from "@/views/sys/components/ResetPassword.vue";
import AddSysUser from "@/views/sys/components/AddSysUser.vue";

// 定义分页属性
const pageInfo = reactive({
    page: 1,
    PageSize: 10,
    keyword: '',
})

// 定义用户数据容器
const tableData = ref([])
// 定义角色数据容器
const rolesData = ref([])
// 定义总数
const total = ref(0)

// 查询用户列表分页信息
const handleLoadData = async () => {
    // 调用系统用户分页接口的方法
    const resp = await FindPageData(pageInfo)
    const dataList = resp.data.list
    tableData.value = dataList.map(data => {
        data.roleIds = data.roleIds ? data.roleIds.split(",").map(m => m * 1) : []
        return data
    })
    total.value = resp.data.total
    pageInfo.page = resp.data.page
}

// multiple 是否多选 emitPath 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
const props = ref({multiple: true, emitPath: false})
// 查询所有的角色信息
const handleFindRoles = async () => {
    // 调用查询角色的接口
    const resp = await FindData()
    rolesData.value = resp.data.map(r => ({label: r.roleName, value: r.id}))
}

// 授予角色
const handleChangeRole = async (row) => {
    // 获取当前授予的用户
    const params = {
        userId: row.id,
        roleIds: row.roleIds.join(",")
    }
    // 调用授权的接口
    await SaveUserRole(params)
    kvaMessage.notifySuccess("用户授予角色成功!")
}

// 点击修改每页大小
const handleSizeChange = (pageSize) => {
    // 改变大小后，从第一页开始重新计算
    pageInfo.page = 1
    // 每页显示多少条数据
    pageInfo.PageSize = pageSize
    // 重新渲染页面
    handleLoadData()
}

// 点击分页改变（翻页）
const handleCurrentChange = (page) => {
    // 当前是第几页
    pageInfo.page = page
    // 重新渲染页面
    handleLoadData()
}

// 修改状态
const handleChangeStatus = async (row, field) => {
    let params = {id: row.id, field}
    if (field == 'enable') {
        params.value = row.enable
    }
    if (field == 'is_deleted') {
        params.value = row.isDeleted
    }

    // 调用修改状态的接口方法
    await UpdateStatus(params)
    kvaMessage.notifySuccess("状态修改成功！")
}

// 删除单个
const handleDelete = async (row) => {
    try {
        const result = await kvaMessage.confirm("删除用户", "您确定要删除吗？")
        if (result === 'confirm') {
            // 调用删除接口
            await DeleteById(row.id)
            kvaMessage.success("删除成功！")
            // 重新渲染数据
            handleLoadData()
        }
    } catch (e) {
        kvaMessage.notifyError("删除失败!")
    }
}

// 获取删除的ids
const ids = ref([])
// 获取选中批量删除的ids
const handleSelectionChange = (rows) => {
    ids.value = rows.map(row => row.id)
}
// 批量删除
const handleBatchDel = async () => {
    // 如果没有选中的行数，提示
    if (ids.value.length === 0) {
        kvaMessage.warning('请选择一项删除的列进行操作!!!')
        return
    }
    const result = await kvaMessage.confirm("批量删除", '你确定执行【批量删除】吗?')
    if (result === 'confirm') {
        const idsStrings = ids.value.join(',')
        console.log('idsStrings', idsStrings)
        await DeleteByIds(idsStrings)
        kvaMessage.success('批量删除成功!')
        // 重新渲染数据
        handleLoadData()
    }
}

// 定义添加和编辑父组件的属性
const addSysUserRef = ref({})
// 添加
const handleAddSysUser = () => {
    addSysUserRef.value.handleOpen()
}
// 编辑
const handleEdit = (row) => {
    addSysUserRef.value.handleOpen(row.id)
}

// 重置密码的组件对象
const userPwdRef = ref({})

// 重置密码点击事件
const handleResetPwd = (row) => {
    userPwdRef.value.handleOpen(row)
}


// 搜索按钮
const handleSearch = () => {
    // 搜索后，重新开始计算
    pageInfo.page = 1
    // 重新渲染页面
    handleLoadData()
}

// 清空按钮
const handleClear = () => {
    // 清空搜索的条件
    pageInfo.keyword = ''
    // 重新渲染页面
    handleLoadData()
}

// 生命周期加载
onMounted(() => {
    handleLoadData()
    handleFindRoles()
})

</script>


<style scoped lang="scss">

</style>
